# coding=utf-8
__author__ = 'luojianbo'
import json
import re, traceback
import toolsutil
import sys

reload(sys)
sys.setdefaultencoding('utf8')


class CaseCauseParser:
    def __load_char(self, conf):
        causes = set()
        for line in open(conf):
            cause = line.strip()
            if len(cause) <= 0:
                continue
            cause = toolsutil.utf8_encode(cause)
            causes.add(cause)
        return list(causes)

    def __init__(self, conf):
        self.__causes = self.__load_char(conf)

    # 删除子串,根据字符串长度
    def __dedup(self, cause_kv):
        norm_causes = set()
        for k, v in sorted(cause_kv.items(), lambda x, y: cmp(x[1], y[1]), reverse=True):
            found = False
            for cause in norm_causes:
                if k in cause:
                    found = True
                    break
            if not found:
                norm_causes.add(k)
        return list(norm_causes)

    # 从正文提取所有案由
    def get_case_causes(self, content):
        results = list()
        content = toolsutil.utf8_encode(content)
        cause_kv = dict()
        for cause in self.__causes:
            if cause in content:
                cause_kv[cause] = len(cause)
        causes = self.__dedup(cause_kv)
        for k, v in sorted(cause_kv.items(), lambda x, y: cmp(x[1], y[1]), reverse=True):
            if k in causes:
                results.append(k)
        return results

    # 获取最有可能的案由
    def get_case_cause(self, content):
        cause = ''
        causes = self.get_case_causes(content)
        if len(causes) > 0:
            cause = causes[0]
        return cause


if __name__ == '__main__':
    parser = CaseCauseParser('../conf/casecause.conf')
    for line in sys.stdin:
        try:
            json_obj = json.loads(line.strip(), encoding='utf8')
            content = json_obj.get('norm_bulletin_content', '').replace('\n', '')
            results = parser.get_case_causes(content)
            cause = parser.get_case_cause(content)
            print content + '\t' + ','.join(results) + '\t' + cause
        except Exception, ex:
            print ex
            continue
